<template>
  <div>
    <el-card>
      <template #header>
        <div class="card-header">
          <span>模板内容</span>
        </div>
      </template>

      <VTable
        :tableData="tableData"
        :options="options"
        @getSelection="handleSelection"
      >
        <template #menubtn>
          <el-button type="primary" @click="handleAdd">新增</el-button>
          <el-button type="warning" @click="handleBatchDelete"
            >批量删除</el-button
          >
        </template>

        <template #operate="scope">
          <el-button
            size="small"
            link
            type="success"
            :icon="Share"
            @click="handleTest(scope.row.id)"
            >测试</el-button
          >
          <el-button
            size="small"
            link
            type="primary"
            :icon="View"
            @click="handleDetail(scope.row)"
            >查看</el-button
          >
          <el-button
            size="small"
            link
            type="primary"
            :icon="Edit"
            @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            size="small"
            link
            type="danger"
            :icon="Delete"
            @click="handleDelete(scope.row.id)"
            >删除</el-button
          >
        </template>
      </VTable>

      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        style="width: 600px"
        @close="resetForm(ruleFormRef)"
      >
        <el-form
          v-if="actionType === '新增' || actionType === '编辑'"
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
        >
          <el-form-item
            v-for="item in filterOptions"
            :key="item"
            :label="item.label"
            :prop="item.prop"
          >
            <el-select
              v-if="item.prop === 'type'"
              v-model="ruleForm[item.prop]"
            >
              <el-option :value="1" label="系统通知"></el-option>
              <el-option :value="2" label="消息通告"></el-option>
            </el-select>
            <el-autocomplete
              :clearable="true"
              v-else-if="item.prop === 'username'"
              v-model="ruleForm[item.prop]"
              :fetch-suggestions="querySearchAdmin"
              class="inline-input w-50"
              @select="handleSelectAdmin"
            />
            <el-input
              v-else
              v-model="ruleForm[item.prop]"
              :rows="5"
              type="textarea"
            ></el-input>
          </el-form-item>
        </el-form>

        <!-- 详情 -->
        <Description
          v-if="actionType === '查看'"
          :options="options"
          :dataItem="dataItem"
        ></Description>
        <template #footer>
          <el-button
            v-if="actionType === '新增' || actionType === '编辑'"
            @click="resetForm(ruleFormRef)"
            >关闭</el-button
          >
          <el-button v-if="actionType === '查看'" @click="dialogVisible = false"
            >关闭</el-button
          >
          <el-button
            v-if="actionType === '新增' || actionType === '编辑'"
            type="primary"
            @click="submitForm(ruleFormRef)"
          >
            确定
          </el-button>
        </template>
      </el-dialog>

      <el-dialog
        v-model="testDialogVisible"
        title="测试"
        style="width: 400px"
        @close="testResetForm(testRuleFormRef)"
      >
        <el-form
          ref="testRuleFormRef"
          :model="testRuleForm"
          :rules="testRules"
          label-width="auto"
        >
          <el-form-item label="接收人" prop="userId">
            <el-autocomplete
              v-model="testRuleForm.username"
              :fetch-suggestions="querySearchUsername"
              clearable
              class="inline-input w-50"
              @select="handleSelectUsername"
              placeholder="请输入接收人"
          /></el-form-item>
        </el-form>

        <template #footer
          ><!-- 测试的按钮 -->
          <el-button @click="testResetForm(testRuleFormRef)">关闭</el-button>
          <el-button type="primary" @click="testSubmit(testRuleFormRef)"
            >测试</el-button
          ></template
        >
      </el-dialog>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import VTable from "../../components/VTable/index.vue";
import Description from "../../components/Description/index.vue";
import { onMounted, ref, reactive } from "vue";
import { addInfoLog } from "../../api/infoManage/index";
import {
  getInfoTemp,
  addInfoTemp,
  updateInfoTemp,
  batchDeleteInfoTemp,
  deleteInfoTemp,
} from "../../api/infoManage";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Edit, View, Plus, List, Share } from "@element-plus/icons-vue";
import {
  getAdminList,
  searchAdmin,
  getUserList,
  searchUser,
} from "../../api/userManage/index";

const tableData = ref<any>([]);
const options = [
  {
    prop: "type",
    label: "类型",
    isTable: true,
    isForm: true,
    type: "info",
  },
  {
    prop: "username",
    label: "发送人名称",
    isTable: true,
    isForm: true,
  },
  {
    prop: "content",
    label: "模板内容",
    isTable: true,
    width: 400,
    isForm: true,
  },
  {
    prop: "createTime",
    label: "创建时间",
    isTable: true,
    type: "time",
  },
];
const filterOptions = options.filter((item) => item.isForm == true);

const dialogTitle = ref("查看"); // 弹出层标题
const dialogVisible = ref<boolean>(false);
const actionType = ref(""); // 操作按钮的类型
const setDialogTile = (type: string) => {
  dialogTitle.value = type;
  actionType.value = type;
  dialogVisible.value = true;
};
const ruleFormRef = ref<FormInstance>();
let ruleForm = reactive({
  userId: Number,
  type: "",
  content: "",
});
const rules = reactive<FormRules>({
  type: [
    { required: true, message: "请选择模板类型", trigger: ["blur", "change"] },
  ],
  username: [
    { required: true, message: "请选择发送人", trigger: ["blur", "change"] },
  ],
  content: [{ required: true, message: "请输入内容", trigger: "blur" }],
});
//新增
const handleAdd = () => {
  ruleForm = reactive({
    userId: "",
    type: "",
    content: "",
  });
  setDialogTile("新增");
};
//编辑
const handleEdit = async (scope: any) => {
  ruleForm = scope;
  setDialogTile("编辑");
};

const testRuleFormRef = ref<FormInstance>();
let testRuleForm = reactive({
  userId: Number,
  infoId: Number,
});
const testRules = reactive<FormRules>({
  userId: [
    { required: true, message: "请选择接收人", trigger: ["blur", "change"] },
  ],
});
//测试
const testDialogVisible = ref<boolean>(false);
const handleTest = (infoId: number) => {
  testRuleForm = reactive({
    userId: "",
    infoId: infoId,
  });
  testDialogVisible.value = true;
};
//提交
const testSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  console.log("test", testRuleForm);
  const res = await addInfoLog(testRuleForm);
  if (res.data.success == true) {
    ElMessage({
      message: res.data.msg,
      type: "success",
    });
    onLoad();
  } else {
    ElMessage.error(res.data.msg);
  }
  testDialogVisible.value = false;
};
//关闭
const testResetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  testDialogVisible.value = false;
};
//自动补全
const querySearchUsername = async (name, callback) => {
  const list = [];
  if (name) {
    const res = await searchUser({ username: name });
    res.data.data.forEach((item: any) => {
      list.push({ value: item.username, id: item.id });
    });
  } else {
    const res = await getUserList();
    res.data.data.forEach((item: any) => {
      list.push({ value: item.username, id: item.id });
    });
  }
  callback(list);
};
//选中
const handleSelectUsername = (item, $event) => {
  console.log(item);
  testRuleForm.userId = item.id;
};

//自动补全
const querySearchAdmin = async (name, callback) => {
  const list = [];
  if (name) {
    const res = await searchAdmin({ username: name });
    res.data.data.forEach((item) => {
      list.push({ value: item.username, id: item.id });
    });
  } else {
    const res = await getAdminList();
    res.data.data.forEach((item) => {
      list.push({ value: item.username, id: item.id });
    });
  }
  callback(list);
};
//选中
const handleSelectAdmin = (item, $event) => {
  ruleForm.userId = item.id;
};

//详情
const dataItem = ref<object>({});
const handleDetail = (scope: any) => {
  dataItem.value = scope;
  setDialogTile("查看");
  console.log("查看", dataItem.value);
};

//删除
const handleDelete = (id: number) => {
  ElMessageBox.confirm("确认删除此项数据?", "系统提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await deleteInfoTemp(id);
      if (res.data.success == true) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
      } else {
        ElMessage.error(res.data.msg);
      }
      await onLoad();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};
//子组件传值--多选
const ids = ref<any>([]);
const handleSelection = (val: any) => {
  console.log("子组件传值：", val);
  const selecction: any = [];
  val.forEach((item: any) => {
    selecction.push(item.id);
  });
  ids.value = selecction;
};
// 批量删除
const handleBatchDelete = async () => {
  if (ids.value.length == 0) {
    ElMessage({
      type: "info",
      message: "请选择数据",
    });
    return;
  }
  ElMessageBox.confirm("确认删除这些数据?", "系统提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await batchDeleteInfoTemp({ ids: ids.value });
      if (res.data.success) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
      } else {
        ElMessage.error(res.data.msg);
      }
      await onLoad();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

//关闭
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  if (actionType.value === "新增") {
    formEl.resetFields();
  }
  dialogVisible.value = false;
};
// 提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  console.log(ruleForm);
  if (actionType.value === "新增") {
    const res = await addInfoTemp(ruleForm);
    if (res.data.success == true) {
      ElMessage({
        message: res.data.msg,
        type: "success",
      });
      onLoad();
    } else {
      ElMessage.error(res.data.msg);
    }
  } else if (actionType.value === "编辑") {
    const res = await updateInfoTemp(ruleForm);
    if (res.data.success) {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
        onLoad();
      } else {
        ElMessage.error(res.data.msg);
      }
    }
  }
  dialogVisible.value = false;
};

const onLoad = async () => {
  const res = await getInfoTemp();
  tableData.value = res.data.data;
  console.log(tableData.value);
};

onMounted(async () => {
  await onLoad();
});
</script>

<style lang="scss" scoped></style>
